package com.atguyigu.codesday02;

                //  synchronized   if   版本的


       /*需求:有一个初始值为零的变量，现有两个线程对该变量操作,实现一个线程对变量加1，实现一个线程对变量减1,交替来10次
          1 高内聚低耦合的前提下，线程   操作 资源类
         2 判断、干活、通知
          */

       //    防止线程的虚假唤醒，使用if判断 演示
class AirCondition {
    int number =0;
  public synchronized void increment()throws Exception{
      // 1判断
      if ( number!=0){
           this.wait();
       }
      //干活
      System.out.println(Thread.currentThread().getName()+"\t"+(++number));
   //3通知
    this.notifyAll();
  }

    public synchronized void decrement()throws Exception{
        // 1判断
        if ( number ==0){
            this.wait();
        }
        //干活
        System.out.println(Thread.currentThread().getName()+"\t"+(--number));
        //3通知
        this.notifyAll();
    }
}

public class ProdConsumerDemo1 {


    public static void main(String[] args) {

        AirCondition airCondition = new AirCondition();

        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                try {
                    airCondition.increment();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        },"A").start();


        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                try {
                    airCondition.decrement();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        },"B").start();


        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                try {
                    airCondition.increment();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        },"c").start();

        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                try {
                    airCondition.decrement();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        },"D").start();
    }
}
